package shuashuami.hb.com.avtivity;

import android.Manifest;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import shuashuami.hb.com.hbclient.R;
import shuashuami.hb.com.hdlibrary.glid.GlidUtil;
import shuashuami.hb.com.hdlibrary.util.ToastUtil;
import shuashuami.hb.com.http.ChangeBUserImageMessageHttp;
import shuashuami.hb.com.http.HttpBMethods;
import shuashuami.hb.com.http.HttpOnNextListener;
import shuashuami.hb.com.share.ShareCUserInfo;
import shuashuami.hb.com.util.FileStorage;
import shuashuami.hb.com.view.BChangeContentDialog;
import shuashuami.hb.com.view.IOSAlertDialog;
import shuashuami.hb.com.view.MyDialog;

public class BUserInfoActivity extends AbActivity implements PermissionListener {


    private ImageView imgHeadImage;
    private TextView tvId, tvUserName, tvRealName, tvqq, tvEmail, tvPhone, tvParentId;

    private GlidUtil glidUtil;

    private LinearLayout llRealName, llQQ, llEmail, llPhone, llParentId;

    private LinearLayout llChangeUserHead;

    private TextView tvShenfenZheng;

    @Override
    protected void initUI() {
        setAbContentView(R.layout.activity_buser_info);
        imgHeadImage = (ImageView) findViewById(R.id.img_cuser_info_user_head);
        tvId = (TextView) findViewById(R.id.tv_cuser_info_id);
        tvUserName = (TextView) findViewById(R.id.tv_cuser_info_user_name);
        tvRealName = (TextView) findViewById(R.id.tv_cuser_info_realname);
        tvqq = (TextView) findViewById(R.id.tv_cuser_info_qq);
        tvEmail = (TextView) findViewById(R.id.tv_cuser_info_email);
        tvPhone = (TextView) findViewById(R.id.tv_cuser_info_phone);
        tvParentId = (TextView) findViewById(R.id.tv_cuser_info_parent_id);

        llRealName = (LinearLayout) findViewById(R.id.ll_cuser_info_real);
        llQQ = (LinearLayout) findViewById(R.id.ll_cuser_info_qq);
        llEmail = (LinearLayout) findViewById(R.id.ll_cuser_info_eamil);
        llPhone = (LinearLayout) findViewById(R.id.ll_cuser_info_phone);
        llParentId = (LinearLayout) findViewById(R.id.ll_cuser_info_parent_id);
        tvShenfenZheng = (TextView) findViewById(R.id.tv_cuser_info_shenfenzheng);


        llChangeUserHead = (LinearLayout) findViewById(R.id.ll_change_user_head);
    }

    @Override
    protected void initData() {
        setTitleBar("个人信息");
        setLeftView();
        glidUtil = new GlidUtil(this);
        getMessage();
    }

    @Override
    protected void initListener() {
        setLeftViewListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BUserInfoActivity.this.finish();
            }
        });
        llRealName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog("realname", tvRealName);
            }
        });
        llQQ.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog("qq", tvqq);
            }
        });
        llEmail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog("email", tvEmail);
            }
        });
        llPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
         //       showDialog("mobile", tvPhone);
            }
        });
        llParentId.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog("parent_id", tvParentId);
            }
        });
        llChangeUserHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imgPhone();
            }
        });
    }

    private void showDialog(String type, TextView tvData) {
        BChangeContentDialog changeContentDialog = new BChangeContentDialog(this, type, tvData);
        changeContentDialog.show();
    }

    public void getMessage() {
        HttpOnNextListener<String> listener = new HttpOnNextListener<String>() {
            @Override
            public void onNext(String s) {
                Message message = handler.obtainMessage(1);     // Message
                message.obj = s;
                handler.sendMessageDelayed(message, 0);

            }
        };
        ShareCUserInfo shareCUserInfo = new ShareCUserInfo(BUserInfoActivity.this);
        HttpBMethods.getBuserInfo(listener,
                shareCUserInfo.getId()
        );
    }

    final Handler handler = new Handler() {

        public void handleMessage(Message msg) {         // handle message
            switch (msg.what) {
                case 1:
                    try {
                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        JSONObject temp = jsonObject.getJSONObject("content");
                        tvUserName.setText(temp.getString("username"));
                        tvId.setText(temp.getString("id"));
                        tvRealName.setText(temp.getString("realname"));
                        tvqq.setText(temp.getString("qq"));
                        tvEmail.setText(temp.getString("email"));
                        tvPhone.setText(temp.getString("mobile"));
                        tvParentId.setText(temp.getString("parent_id"));
                        tvShenfenZheng.setText(temp.getString("identify"));
                        glidUtil.uploadCircle(temp.getString("avatar"), imgHeadImage, R.mipmap.ssm_icon_11);
                    } catch (JSONException e) {
                        ToastUtil.showShort(BUserInfoActivity.this, "数据解析错误");
                    }


                    break;
            }

            super.handleMessage(msg);
        }
    };

    private Uri imageUri;// 原图保存地址
    private boolean isClickCamera = false;// 是否拍照
    private String imagePath;

    private List<File> list = new ArrayList<>();
    private List<String> filePath;
    private File iconPath = null;
    private File cropPath = null;
    private static final int REQUEST_PICK_IMAGE = 101; // 相册选取
    private static final int REQUEST_CAPTURE = 102; // 拍照
    private static final int REQUEST_PICTURE_CUT = 103; // 剪裁图片
    private static final int REQUEST_CODE_SETTING = 300;

    private static final int REQUEST_CODE_PERMISSION_SD = 100;
    private static final int REQUEST_CODE_PERMISSION_OTHER = 101;

    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA};

    MyDialog dialog;

    class poponDismissListener implements PopupWindow.OnDismissListener {
        @Override
        public void onDismiss() {
            backgroundAlpha(1f);
        }
    }

    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
    }

    private void imgPhone() {
        dialog = new MyDialog(this);
        // TODO Auto-generated method stub
        TextView tv1 = dialog.getTakePhone();
        TextView tv2 = dialog.getSystemphone();
        tv1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dialog.dismiss();
                if (Build.VERSION.SDK_INT >= 23) {
                    AndPermission.with(BUserInfoActivity.this)
                            .requestCode(REQUEST_CODE_PERMISSION_SD)
                            .permission(PERMISSIONS)
                            .rationale(new RationaleListener() {

                                @Override
                                public void showRequestPermissionRationale(
                                        int requestCode, Rationale rationale) {
                                    // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                                    AndPermission.rationaleDialog(
                                            BUserInfoActivity.this, rationale)
                                            .show();
                                }
                            }).send();
                } else {
                    openCamera();
                }
                isClickCamera = true;
            }
        });
        tv2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dialog.dismiss();
                if (Build.VERSION.SDK_INT >= 23) {
                    AndPermission.with(BUserInfoActivity.this)
                            .requestCode(REQUEST_CODE_PERMISSION_OTHER)
                            .permission(PERMISSIONS)
                            .rationale(new RationaleListener() {

                                @Override
                                public void showRequestPermissionRationale(
                                        int requestCode, Rationale rationale) {
                                    // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                                    AndPermission.rationaleDialog(
                                            BUserInfoActivity.this, rationale)
                                            .show();
                                }
                            }).send();
                } else {
                    // Toast.makeText(FeedbackActivity.this,
                    // "FeedbackActivity", Toast.LENGTH_SHORT).show();
                    selectFromAlbum();
                }
                isClickCamera = false;
            }
        });
        dialog.show();
    }

    /**
     * 打开系统相机(这个方法已经适配android7.0中的私有目录被限制访问权限)
     * 从Android7.0开始在应用间共享文件时已经不允许使用intent来传递file://URI类型的uri了
     * 只允许传递content://URI类型的uri
     */
    private void openCamera() {
        File file = new FileStorage().createIconFile();
        iconPath = file;
        // 判断当前的SDK版本是否在7.0及以上
        // 是的话就使用最新的文件传递机制，否则就使用老的文件传递机制
        if (Build.VERSION.SDK_INT >= 24) {
            // 通过FileProvider创建一个content类型的Uri
            imageUri = FileProvider.getUriForFile(BUserInfoActivity.this,
                    "shuashuami.hb.com.hbclient.fileprovider", file);
        } else {
            imageUri = Uri.fromFile(file);
        }
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= 24) {
            // 添加这一句表示对目标应用临时授权该Uri所代表的文件(授予 URI 临时访问权限)
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);// 设置Action为拍照
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);// 将拍取的照片保存到指定URI
        startActivityForResult(intent, REQUEST_CAPTURE);
    }

    /**
     * 从相册选择
     */
    private void selectFromAlbum() {
        Intent intent = new Intent(Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, REQUEST_PICK_IMAGE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] grantResults) {
        AndPermission.onRequestPermissionsResult(requestCode, permissions,
                grantResults, this);
    }

    @Override
    public void onFailed(int arg0, List<String> arg1) {
        // TODO Auto-generated method stub
        switch (arg0) {
            case REQUEST_CODE_PERMISSION_SD: {
                // Toast.makeText(this, "请打开必要权限", Toast.LENGTH_SHORT).show();
                showTipsDialog();
                break;
            }
            case REQUEST_CODE_PERMISSION_OTHER: {
                // Toast.makeText(this, "请打开必要权限", Toast.LENGTH_SHORT).show();
                showTipsDialog();
                break;
            }
        }
        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(this, arg1)) {
        }
    }

    /**
     * 显示提示对话框
     */
    private void showTipsDialog() {
        IOSAlertDialog dialog = new IOSAlertDialog(this);
        dialog.builder().setTitle("提示")
                .setMessage("当前应用缺少相机权限。\n请到\"设置\"-\"权限\"-打开所需权限。")
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                    }

                }).show();
    }

    @Override
    public void onSucceed(int arg0, List<String> arg1) {
        // TODO Auto-generated method stub
        switch (arg0) {
            case REQUEST_CODE_PERMISSION_SD:
                openCamera();
                break;
            case REQUEST_CODE_PERMISSION_OTHER:
                selectFromAlbum();
                break;
        }
    }

    private void handleImageOnKitKat(Intent data) {
        imagePath = null;
        try {
            imageUri = data.getData();
            if (DocumentsContract.isDocumentUri(this, imageUri)) {
                // 如果是document类型的uri,则通过document id处理
                String docId = DocumentsContract.getDocumentId(imageUri);
                if ("com.android.providers.media.documents".equals(imageUri
                        .getAuthority())) {
                    String id = docId.split(":")[1];// 解析出数字格式的id
                    String selection = MediaStore.Images.Media._ID + "=" + id;
                    imagePath = getImagePath(
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            selection);
                } else if ("com.android.downloads.documents".equals(imageUri
                        .getAuthority())) {
                    Uri contentUri = ContentUris.withAppendedId(
                            Uri.parse("content://downloads/public_downloads"),
                            Long.valueOf(docId));
                    imagePath = getImagePath(contentUri, null);
                }
            } else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
                // 如果是content类型的Uri，则使用普通方式处理
                imagePath = getImagePath(imageUri, null);
            } else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
                // 如果是file类型的Uri,直接获取图片路径即可
                imagePath = imageUri.getPath();
            }
            cropPhoto();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    private void handleImageBeforeKitKat(Intent intent) {
        imageUri = intent.getData();
        imagePath = getImagePath(imageUri, null);
        cropPhoto();
    }

    /**
     * 裁剪
     */
    private void cropPhoto() {
        File file = new FileStorage().createCropFile();
        cropPath = file;
        Uri outputUri = Uri.fromFile(file);// 缩略图保存地址
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= 24) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.setDataAndType(imageUri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, REQUEST_PICTURE_CUT);
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过Uri和selection老获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null,
                null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void upload(File file) {
        List<String> images = new ArrayList<>();
        images.add(file.getAbsolutePath());
        ChangeBUserImageMessageHttp changeCUserImageMessageHttp = new ChangeBUserImageMessageHttp(this, imgHeadImage);
        changeCUserImageMessageHttp.uploadImg(images);
    }


    private void addPhoto(String imgPath, Uri imgUri) {
        list.clear();

        if (imgUri != null) {
            glidUtil.uploadCircle(iconPath.getAbsolutePath(), imgHeadImage, R.mipmap.ssm_icon_11);
            upload(iconPath);
        } else {
            glidUtil.uploadCircle(cropPath.getAbsolutePath(), imgHeadImage, R.mipmap.ssm_icon_11);
            upload(cropPath);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_PICK_IMAGE:// 从相册选择
                if (Build.VERSION.SDK_INT >= 19) {
                    handleImageOnKitKat(data);
                } else {
                    handleImageBeforeKitKat(data);
                }
                break;
            case REQUEST_CAPTURE:// 拍照
                addPhoto("", imageUri);
                break;
            case REQUEST_PICTURE_CUT:// 裁剪完成
                try {
                    addPhoto(imagePath, null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case REQUEST_CODE_SETTING:
                Toast.makeText(this, "从设置返回", Toast.LENGTH_LONG).show();
                break;
        }

    }
}
